<template>
  <div id="city">
    <van-index-bar :index-list="indexList">
      <div v-for="item in cityList" :key="item.prefix">
        <van-index-anchor index="item.prefix">{{
          item.prefix.toUpperCase()
        }}</van-index-anchor>
        <div v-for="data in item.cities" :key="data.cityId">
          <van-cell :title="data.name" @click="cityText(data)" />
        </div>
      </div>
    </van-index-bar>
  </div>
</template>
<script>
import { IndexBar, IndexAnchor, Cell } from "vant";
import { computed, onMounted } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
export default {
  components: {
    [IndexBar.name]: IndexBar,
    [IndexAnchor.name]: IndexAnchor,
    [Cell.name]: Cell,
  },
  setup() {
    // 拿到store对象
    const store = useStore();
    //路由对象
    const router = useRouter();
    // 在mouted中使用 actions
    onMounted(() => {
      store.dispatch("city/cityData");
    });
    //点击每个数据存到本地仓库供给主页面使用
    function cityText(data) {
      localStorage.setItem("cityName", data.name);
      localStorage.setItem("cityId", data.cityId);
      router.push("/home");
    }
    return {
      cityText,
      cityList: computed(() => store.state.city.getCityList), //获取城市的数据
      indexList: computed(() => store.getters["city/indexList"]), //获取城市的字母数据
    };
  },
};
</script>
<style lang="less" scoped>
#city {
  /deep/.van-index-anchor {
    background-color: #eee;
  }
  /deep/ .van-cell {
    border-bottom: 1px solid #ddd;
  }
}
</style>
